package com.shawn.springboot.integeration.websocket.session;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 客户端用户集
 */
@Slf4j
public class WebSocketSessions {
    private static Map<String, Session> SESSIONS = new ConcurrentHashMap<>();

    public static void put(String key, Session session) {
        SESSIONS.put(key, session);
    }

    public static boolean remove(String key) {
        log.info("\n 正在移出用户 - {}", key);
        Session remove = SESSIONS.remove(key);
        if (remove != null) {
            boolean containsValue = SESSIONS.containsValue(remove);
            String rmRes = containsValue ? "失败" : "成功";
            log.info("\n 移出结果 - {}", rmRes);
            return containsValue;
        } else {
            return true;
        }
    }
    public static Map<String, Session> getSessions() {
        return SESSIONS;
    }

    public static void broadcastByText(String msg) {
        Collection<Session> values = SESSIONS.values();
        for (Session value : values) {
            sendMsgToUserByText(value, msg);
        }
    }
    public static void sendMsgToUserByText(Session session, String msg) {
        if (session != null) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                log.error("\n[发送消息异常]", e);
            }
        } else {
            log.info("\n[你已离线]");
        }
    }
}
